package the_art_of_java_concurrency_programming.concurrent.Lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: 李浩然
 * @Date: 2021/6/6 4:35 下午
 */
public class Cache {
    static Map<String, Object> map = new HashMap<String, Object>();
    static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    static Lock r = rwl.readLock();
    static Lock w = rwl.writeLock();
    static volatile boolean update =false;
    public static final Object get(String key) {
        r.lock();
        try {
            return map.get(key);
        } finally {
            r.unlock();
        }
    }

    public static final Object put(String key, Object value) {
        w.lock();
        try {
            return map.put(key, value);
        } finally {
            w.unlock();
        }
    }

    public static final void clear(){
        w.lock();
        try {
            map.clear();
        }finally {
            w.unlock();
        }
    }

    //锁降级->将写锁降级为读锁
    public void processData(){
        r.lock();
        if(!update){
            //必须先释放锁
            r.unlock();
            //锁降级从写锁获取开始
            w.lock();
            try {
                if(!update){
                    //准备数据的过程
                    update=true;
                }
                r.lock();
            }finally {
                w.unlock();
            }
        }
        try{
            //使用数据的过程(略)
        }finally {
            r.unlock();
        }
    }
}
